/**
 * IHIS 1.0 by HoneyBread (김민호, 이충희, 이성연, 신경민)
 * SEP 8기 KAIST
 */
package ihis.tms.server.service;

import ihis.core.service.RequestMessage;
import ihis.core.service.ResponseMessage;

import java.util.HashMap;
import java.util.Map;

import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.util.SessionLog;

/**
 * @author minho kim
 *
 */
public abstract class ServerSessionhandler extends IoHandlerAdapter {
	protected Map<Integer, IService> serviceMap = new HashMap<Integer, IService>();
	
	public ServerSessionhandler() {
		initService();
	}
	
	abstract protected void initService();
	
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		session.setIdleTime(IdleStatus.BOTH_IDLE, 60);
	}
	
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		if((message instanceof RequestMessage) == false){
			return;
		}
		
		RequestMessage requestMessage = (RequestMessage) message;
		ResponseMessage responseMessage = null;
		
		IService service = serviceMap.get(requestMessage.getServiceId());
		
		if(service != null){
			responseMessage = service.run(requestMessage);
		} else {
			responseMessage = new ResponseMessage();
			responseMessage.setErrorMessage("Sevice Call is invalid");
			responseMessage.setOk(false);
		}
		
		session.write(responseMessage);
	}
	
	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		SessionLog.info(session, "Disconnecting the idle."); //$NON-NLS-1$
		session.close();
	}
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		session.close();
	}
}
